package com.zhong.blog.controller;


import com.zhong.blog.pojo.User;
import com.zhong.blog.service.UserService;
import com.zhong.blog.utlis.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
//@CrossOrigin
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/register")
    public R register(@RequestBody @Valid User user, BindingResult bindingResult){
        System.out.println("==========");
        System.out.println(user.toString());
        //  数据校验
        if (bindingResult.hasErrors()){
            System.out.println("校验错误");
            Map<String,String> map=new HashMap<>();
            bindingResult.getFieldErrors().forEach((item)->{
                String message = item.getDefaultMessage();
                String field = item.getField();
                map.put(field,message);
            });
            System.out.println(map.toString());
            return R.error(400,"提交数据不合法").put("data",map);
        }
        List<User> users = userService.queryAll();
        for (User queryUser : users) {
            if (user.getUsername().equals(queryUser.getUsername())){
                return R.error().put("error","用户名已注册");
            }
        }
        //
        userService.save(user);
        return R.ok();
    }

    @PostMapping("/login")
    public R login(@RequestBody User user){
        System.out.println(user.toString());
        int count = userService.query(user);
        if (count == 1){
            System.out.println("成功");
            return R.ok();
        }else {
            System.out.println("失败");
            return R.error();
        }
    }

    @PostMapping("/user/queryByName")
    public R queryByName(@RequestParam("name") String name){
        System.out.println("参数用户名："+name);
        List<User> users = userService.queryByName(name);
        System.out.println(users.size());
        if (users.size() > 1){
            return R.error().put("error","查询用户有多个");
        }else if (users.size() == 0){
            return R.error().put("error","没有此用户");
        }else {
            return R.ok().put("user",users);
        }
    }




}
